package com.string.actortv.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.annotation.Nullable;
import cn.hutool.core.date.DateUtil;
import com.aliyun.player.AliPlayer;
import com.aliyun.player.AliPlayerFactory;
import com.aliyun.player.nativeclass.PlayerConfig;
import com.aliyun.player.source.UrlSource;
import com.string.actortv.R;
import com.string.actortv.util.SQLiteHelper;

import java.util.Date;

public class AliPlayerActivity extends Activity {

    private final static long PASS_TIME = 5000;

    private AliPlayer mAliVideo;
    private SurfaceView surfaceView;
    private Long playTime;
    private Long pauseTime;
    private int playStatus = 1;
    private SeekBar mSeekBar;
    private TextView mCurrentText;
    private TextView mLengthText;
    private SQLiteHelper sqLiteHelper;
    private long duration = 0;
    private Context mContext;
    private AlertDialog.Builder mDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ali_player);
        mContext = this;
        sqLiteHelper = new SQLiteHelper(mContext);

        Intent intent = getIntent();
        if (intent == null) {
            onBackPressed();
            return;
        }

        //屏幕横屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        //隐藏顶部任务栏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        mSeekBar = findViewById(R.id.dp_game_progress);
        mCurrentText = findViewById(R.id.listen_current_tv);
        mLengthText = findViewById(R.id.listen_length_tv);

        surfaceView = findViewById(R.id.ijkPlayer);
        surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                mAliVideo.setDisplay(holder);
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                mAliVideo.redraw();
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                mAliVideo.setDisplay(null);
            }
        });

        mAliVideo = AliPlayerFactory.createAliPlayer(getApplicationContext());

        if (intent.hasExtra("cookie")) {
            String cookie = "FTN5K=" + intent.getStringExtra("cookie").toLowerCase();
            PlayerConfig config = mAliVideo.getConfig();
            String[] headers = new String[1];
            headers[0] = "cookie:" + cookie;
            config.setCustomHeaders(headers);
            mAliVideo.setConfig(config);
        }

        //换成自己的播放地址
        String playUrl = intent.getStringExtra("playUrl");
        UrlSource urlSource = new UrlSource();
        urlSource.setUri(playUrl);

        //设置播放结束事件，结束后自动返回上一页面
        mAliVideo.setOnCompletionListener(this::finish);

        mAliVideo.setOnErrorListener(errorInfo -> {
            mDialog = new AlertDialog.Builder(mContext);
            mDialog.setTitle("播放错误");
            mDialog.setMessage("错误信息：" + errorInfo.getMsg());
            mDialog.setPositiveButton("确定", (dialog, which) -> {
                finish();
            }).setCancelable(false).create().show();
        });

        //设置播放进度控制
        mAliVideo.setOnVideoRenderedListener((l, l1) -> {
            mSeekBar.setMax(Math.toIntExact(duration));
            mSeekBar.setProgress(Math.toIntExact(System.currentTimeMillis() - playTime));
            mCurrentText.setText(DateUtil.format(new Date(System.currentTimeMillis() - playTime - 8 * 60 * 60 * 1000), "HH:mm:ss"));
            mLengthText.setText(DateUtil.format(new Date(duration - 8 * 60 * 60 * 1000), "HH:mm:ss"));
        });

        mAliVideo.setOnPreparedListener(() -> {
            duration = mAliVideo.getDuration();
            Log.d("preparedTimes", "" + intent.getLongExtra("hisTimes", 0L));
            playTime = System.currentTimeMillis() - intent.getLongExtra("hisTimes", 0L);
            mAliVideo.seekTo(intent.getLongExtra("hisTimes", 0L));
        });


        //设置播放源
        mAliVideo.setDataSource(urlSource);
        mAliVideo.setAutoPlay(true);

        //准备播放
        mAliVideo.prepare();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == 0) {
            Log.d("dispatchKeyEvent", "" + event.getKeyCode());
            switch (event.getKeyCode()) {
                case KeyEvent.KEYCODE_ENTER:
                case KeyEvent.KEYCODE_DPAD_CENTER:
                    if (playStatus == 1) {
                        playStatus = 0;
                        pauseTime = System.currentTimeMillis();
                        mAliVideo.pause();
                    } else {
                        playStatus = 1;
                        playTime = System.currentTimeMillis() - pauseTime + playTime;
                        mAliVideo.start();
                    }
                    break;
                case KeyEvent.KEYCODE_DPAD_DOWN:
                    //TODO 下方向键
                    break;
                case KeyEvent.KEYCODE_DPAD_LEFT:
                    if (playStatus == 1) {
                        mAliVideo.seekTo(System.currentTimeMillis() - playTime - PASS_TIME);
                    } else {
                        mAliVideo.seekTo(pauseTime - playTime - PASS_TIME);
                    }
                    playTime += PASS_TIME;
                    break;
                case KeyEvent.KEYCODE_DPAD_RIGHT:
                    if (playStatus == 1) {
                        mAliVideo.seekTo(System.currentTimeMillis() - playTime + PASS_TIME);
                    } else {
                        mAliVideo.seekTo(pauseTime - playTime + PASS_TIME);
                    }
                    playTime -= PASS_TIME;
                    break;
                case KeyEvent.KEYCODE_DPAD_UP:
                    //TODO 上方向键
                    break;
                default:
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!mAliVideo.isAutoPlay()) {
            mAliVideo.start();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        mAliVideo.pause();
        destroy();
    }

    private void destroy() {
        //记录退出时的播放时长
        long nowTime = System.currentTimeMillis() - (playTime == null ? System.currentTimeMillis() : playTime);
        Log.d("hisTimes", "" + nowTime);
        String percent = nowTime * 100 / mAliVideo.getDuration() + "%";
        if (nowTime + 3000 >= mAliVideo.getDuration()) {
            nowTime = 0;
        }
        if (nowTime > 1000) {
            nowTime -= 2000;
        }
        sqLiteHelper.updateHistoryTimes(getIntent().getExtras().getString("url"), nowTime, percent);
    }

    @Override
    protected void onDestroy() {
        mAliVideo.release();
        super.onDestroy();
    }

}
